#!/sbin/openrc-run

description="Step CA"
description_check="Verify configuration"

config_dir="${STEPPATH:-/etc/step-ca}"
pidfile="/run/$RC_SVCNAME.pid"
command="/usr/bin/step-ca"
command_args="${config_dir}/config/ca.json --password-file=${config_dir}/password.txt"
command_background="yes"
command_user="step-ca:step-ca"
start_stop_daemon_args="--env STEPPATH=${STEPPATH} --stdout /var/log/$RC_SVCNAME/${RC_SVCNAME}.log --stderr /var/log/$RC_SVCNAME/${RC_SVCNAME}.err"
extra_commands="checkconfig"

required_files="${config_dir}/config/ca.json ${config_dir}/password.txt"

depend() {
	use logger dns
	after entropy networking
}

start_pre() {
	checkconfig

	command_args="${command_args} ${EXTRA_ARGS}"

	if [ "x${ENTROPY_COUNT}" != "x" ]; then
		command_args="${command_args} -e ${ENTROPY_COUNT}"
	fi
}

checkconfig() {
	if [ ! -d /var/log/step-ca ]; then
		mkdir -p /var/log/step-ca
		chown -R step-ca:step-ca /var/log/step-ca
		chmod -R 700 /var/log/step-ca
	fi

	if [ ! -d ${config_dir} ]; then
		mkdir -p ${config_dir}
		chown -R step-ca:step-ca ${config_dir}
		chmod -R 700 ${config_dir}
	fi

	if [ ! -f ${config_dir}/config/ca.json ]; then
		ewarn "CA configuration file is missing"
	fi

	if [ ! -f ${config_dir}/password.txt ]; then
		ewarn "CA password file is missing"
	fi
}
